package com.ruoyi.gzmx.in_phd;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Component;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.gzmx_scdw.domain.Tag_result;
import com.ruoyi.gzmx_tag_history.domain.Gzmx_tag_history;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset; 
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.Source;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;


@Component("in_phd")
public class in_phd {
	
	 static int socketTimeout = 100000;// 请求超时时间
	 static int connectTimeout = 100000;// 传输超时时间
	 static final String soap = "text/xml;charset=UTF-8";
	 static final String soap11 = "application/soap+xml;charset=UTF-8";
	
	public String test3(@RequestBody String xmlString) throws javax.xml.rpc.ServiceException{
		
		System.out.println(xmlString);
		String wsdlUrl ="http://a11.hbyt.petrochina/A11Service/webservice/well/rtDataService?wsdl";
		//Uri uri = new Uri("http://a11.hbyt.petrochina/A11Service/webservice/well/rtDataService?wsdl")
		//看具体响应的WSDL中的namespace
		String nameSpaceUri ="http://service.btmp.com/";    
		Service service = new Service();
		Call call;
		String returnvalue = "";
		try {
			call = (Call)service.createCall();
			call.setTargetEndpointAddress(wsdlUrl);
			 //设置operation 名称，
			call.setOperationName(new QName(nameSpaceUri, "getDCGH"));
			call.addParameter("gysbm", org.apache.axis.Constants.XSD_STRING,ParameterMode.IN);
			call.addParameter("authdata",org.apache.axis.Constants.XSD_STRING,ParameterMode.IN);
			call.addParameter("xmlString",org.apache.axis.Constants.XSD_STRING,ParameterMode.IN);
			//设置返回类型为对象数组
			call.setReturnClass(Object[].class);
			SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
			String pwd = "hbA11Service"+"A11Service_HB";//+sf.format(new Date());//账户&密码&当天日期
			System.out.println(sf.format(new Date()));
			System.out.println("pwd=" + pwd);
			   //soap.Append("<username>hbA11Service</username>");
	           // soap.Append("<password>A11Service_HB</password>");
			Object[] objs = (Object[]) call.invoke(new Object[]{"M107530000",pwd, xmlString });//M107530000
			
			//System.out.println("objs="+objs);
			
			System.out.println((String)objs[0]);
			System.out.println((String)objs[1]);
			returnvalue = (String)objs[0];
			
			String result = (String)objs[2];
			
			System.out.println("result="+result);
		} catch (ServiceException e1) {
			
			e1.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
        return returnvalue;
    }

	/**
	    * 同步HttpPost请求发送SOAP格式的消息
	      * 
	     * @param webServiceURL
	      *            WebService接口地址
	    * @param soapXml
	     *            消息体
	      * @param soapAction
	      *            soapAction
	      * @param soapType
	     *            soap版本
	      * @return
	      */
	     public static String doPostSoap(String webServiceURL, String qy_cs,String str_password,String username,String soapXml,String soapAction, String soapType) {
	 //        BufferedReader reader = null;  
	         // 创建HttpClient
	         HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	         
	         CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
	        // 创建Post请求
	         //webServiceURL="http://a11.hbyt.petrochina/A11Service/webservice/well/rtDataService?wsdl";
	         //qy_cs="75O35LVnS";
	         soapXml="";
	         soapXml+="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.commwell.well.webservice.a11.cnpcrt.com/\">";
	         soapXml+="<soapenv:Header>";
	         soapXml+="<authHeader>";
	         //soapXml+="<username>hbA11Service</username>";
	         //soapXml+="<password>A11Service_HB</password>";
	         soapXml+="<username>"+str_password+"</username>";
	         soapXml+="<password>"+username+"</password>";
	         soapXml+="</authHeader>";
	         soapXml+="</soapenv:Header>";
	         soapXml+="<soapenv:Body>";
	         soapXml+="<ser:getStationRtData>";
	         soapXml+="<arg0>" + qy_cs + "</arg0>";
	         soapXml+="</ser:getStationRtData>";
	         soapXml+="</soapenv:Body>";
	         soapXml+="</soapenv:Envelope>";
	         soapAction="";
	         soapType="text/xml;charset=UTF-8";
	         HttpPost httpPost = new HttpPost(webServiceURL);
	         // 设置请求和传输超时时间
	         RequestConfig requestConfig = RequestConfig.custom()
	                .setSocketTimeout(socketTimeout)
	                .setConnectionRequestTimeout(socketTimeout)
	                .setConnectTimeout(connectTimeout).build();
	        httpPost.setConfig(requestConfig);
	        // 设置Post请求报文头部
	        httpPost.setHeader("Content-Type", soapType);
	        httpPost.setHeader("SOAPAction", soapAction);
	        // 添加报文内容
	         StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
	         httpPost.setEntity(data);
	        try {
	           // 执行请求获取返回报文
	             CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
	             HttpEntity httpEntity = response.getEntity();
	             if (httpEntity != null) {
	                // 打印响应内容
	            	 
	            	 return EntityUtils.toString(httpEntity, "UTF-8");
	             }
	 //            if (httpEntity != null) {  
	//                reader = new BufferedReader(new InputStreamReader(httpEntity .getContent(), "UTF-8"));  
	 //                StringBuffer sb = new StringBuffer();  
	 //                String line = null;  
	 //                while ((line = reader.readLine()) != null) {  
	 //                    sb.append(line);  
	 //                    sb.append("\r\n");  
	//                }  
	//                return sb.toString();  
	 //            }  
	             // 释放资源
	             closeableHttpClient.close();
	         } catch (ClientProtocolException e) {
	        	System.out.println("e---"+e.toString());
	             e.printStackTrace();
	         } catch (IOException e) {
	        	 System.out.println("IOExceptione---"+e.toString());
	             e.printStackTrace();
	        }
	         return null;
	     }
	    // public static WebserviceResultBean parseSoapMessage(String soapXML) {
	     public List<Gzmx_tag_history> parseSoapMessage(String soapXML) {
	    	 if(StringUtils.isEmpty(soapXML)){
	    	 	return new ArrayList<>();
			 }
	    	 
	    	 List<Tag_result> list=new ArrayList();
	    	 List<Gzmx_tag_history> list_gzmx_tag_history=new ArrayList();
	    		 
	    	 //WebserviceResultBean resultBean = new WebserviceResultBean();
	    	 Tag_result tag_result=new Tag_result();
	    	 try {

	    	 SOAPMessage msg = formatSoapString(soapXML);

	    	 SOAPBody body = msg.getSOAPBody();

	    	 Iterator iterator = body.getChildElements();
	    	 
	    	 //Tag_result tag_result_new=new  Tag_result();

	    	 //tag_result_new=parse(iterator, tag_result);
	    	//
	    	 int ii=0;
	    	 
	    	 //while (iterator.hasNext()) {
	    		 SOAPElement element_new = (SOAPElement) iterator.next();
	    		
		    	 Iterator it_new = element_new.getChildElements();
		    	 
		    	 //System.out.println("element_new.getNodeName()--"+element_new.getNodeName());
		    	 while(it_new.hasNext()){
		    		 SOAPElement element = (SOAPElement) it_new.next();
		    		 Iterator it_new_new = element.getChildElements();
		    		 Tag_result tag_result_new=new  Tag_result();
		    		 Gzmx_tag_history gzmx_tag_history=new Gzmx_tag_history();
		    		 while(it_new_new.hasNext()){
		    			 
		    			 SOAPElement element_new_new = (SOAPElement) it_new_new.next();
		    			 if ("value".equals(element_new_new.getNodeName())) {

				    		 tag_result_new.setValue(Float.valueOf(element_new_new.getValue()));
				    		 gzmx_tag_history.setValue(Float.valueOf(element_new_new.getValue()));

					    	 } 
                         if ("paramConfigId".equals(element_new_new.getNodeName())) {

					    		 tag_result_new.setParamConfigId(Long.valueOf(element_new_new.getValue()));
					    		 gzmx_tag_history.setParamConfigId(Long.valueOf(element_new_new.getValue()));

					    	 } 
                         if ("tag".equals(element_new_new.getNodeName())) {
                        	
					    		 tag_result_new.setTag(element_new_new.getValue());
					    		 gzmx_tag_history.setSourceTag(element_new_new.getValue());
					    	 }
                         if ("time".equals(element_new_new.getNodeName())) {
                        	//DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss");
                        	DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
                        	
                        	 LocalDateTime endTime = LocalDateTime.parse(element_new_new.getValue(),formatter);
                        	 String da_time= endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                        	  
                        	 String format = "yyyy-MM-dd HH:mm:ss";                             
                             SimpleDateFormat sdf = new SimpleDateFormat(format);
                             Date date=sdf.parse(da_time);
                             System.out.println("date---"+date);
				    		 //Date date=Date.from(endTime.atZone(ZoneId.systemDefault()).toInstant());
				    		 
                        	 tag_result_new.setTime(date);
                        	 gzmx_tag_history.setCj_time(date);
				    	 }
                         if ("paramDesc".equals(element_new_new.getNodeName())) {

				    		 tag_result_new.setParamDesc(element_new_new.getValue());
				    		 gzmx_tag_history.setDescription(element_new_new.getValue());
				    	 }
                         
		    			// System.out.println("element_new_new.getNodeName()--"+element_new_new.getNodeName()+":"+element_new_new.getValue());
		    		 }
		    		 list.add(tag_result_new);	 
		    		 list_gzmx_tag_history.add(gzmx_tag_history);
		             
		         }
	    		while(it_new.hasNext()) {//}
	    			
	    			/*
	    		System.out.println("ii--"+ii);
	    			
		    	System.out.println("element111--"+(SOAPElement) it_new.next());
	    		 SOAPElement element = (SOAPElement) it_new.next();
	    		 System.out.println(element.getChildElements().hasNext());
		    	 System.out.println("element.getNodeName()--"+element.getNodeName());
		    	 if ("/return".equals(element.getNodeName())) {

			    	 continue;
			    	
			    	 }else if("return".equals(element.getNodeName())) {
			    		 ii++;
			    		 Iterator it = element.getChildElements();
			    		 Tag_result tag_result_new=new  Tag_result();
				    	 SOAPElement el = null;
				    	 while (it.hasNext()) {
					    	 el = (SOAPElement) it.next();
					    	 if ("value".equals(el.getLocalName())) {

					    		 tag_result_new.setValue(Float.valueOf(el.getValue()));

						    	 } else if ("paramConfigId".equals(el.getLocalName())) {

						    		 tag_result_new.setParamConfigId(Long.valueOf(el.getValue()));

						    	 } else if ("tag".equals(el.getLocalName())) {

						    		 tag_result_new.setTag(el.getValue());
						    	 }
					    	 list.add(tag_result_new);	 
				    	 }
			    		 
			    	 }*/
	    	 }
	    	// }
	    	
	    	 
	    	 //list.add(tag_result_new);
	    	
	    	  //list=parse_list(it_new, tag_result);

	    	 } catch (Exception e) {

	    	 e.printStackTrace();

	    	 }

	    	 return list_gzmx_tag_history;

	    	 }




	public static SOAPMessage formatSoapString(String soapString) {

	    	 MessageFactory msgFactory;

	    	 try {

	    	 msgFactory = MessageFactory.newInstance();

	    	 SOAPMessage reqMsg = msgFactory.createMessage(new MimeHeaders(),

	    	 new ByteArrayInputStream(soapString.getBytes("UTF-8")));

	    	 reqMsg.saveChanges();

	    	 return reqMsg;

	    	 } catch (Exception e) {

	    	 e.printStackTrace();

	    	 return null;

	    	 }

	    	 }
	    	 
	     private Tag_result parse(Iterator iterator, Tag_result tag_result) {

	    	 while (iterator.hasNext()) {

	    	 SOAPElement element = (SOAPElement) iterator.next();

	    	 if ("/return".equals(element.getNodeName())) {

	    	 continue;
	    	 

	    	 } else if ("return".equals(element.getNodeName())) {

	    	 Iterator it = element.getChildElements();

	    	 SOAPElement el = null;

	    	 while (it.hasNext()) {

	    	 el = (SOAPElement) it.next();
	    	 System.out.println("el--"+el);
	    	 if ("value".equals(el.getLocalName())) {

	    	  tag_result.setValue(Float.valueOf(el.getValue()));

	    	System.out.println("#### " + el.getLocalName() + " ==== " + el.getValue());

	    	 } else if ("paramConfigId".equals(el.getLocalName())) {

	    		 tag_result.setParamConfigId(Long.valueOf(el.getValue()));

	    	 System.out.println("#### " + el.getLocalName() + " ==== " + el.getValue());

	    	 } else if ("tag".equals(el.getLocalName())) {

	    		 tag_result.setTag(el.getValue());

	    	 System.out.println("#### " + el.getLocalName() + " ==== " + el.getValue());

	    	 }

	    	 }

	    	 } else if (null == element.getValue()&& element.getChildElements().hasNext()) {

	    	 parse(element.getChildElements(), tag_result);

	    	 }
	    	 }
	    	 return tag_result;
	    	 }
	     
	     
	     
	     private List<Tag_result> parse_list(Iterator iterator, Tag_result tag_result_new) {

	    	 List<Tag_result> list=new ArrayList();
	    	 
	    	 while (iterator.hasNext()) {

	    	 SOAPElement element = (SOAPElement) iterator.next();

	    	 if ("/return".equals(element.getNodeName())) {

	    	 continue;
	    	 

	    	 } else if ("return".equals(element.getNodeName())) {
	    		 
	    	 Tag_result tag_result=new Tag_result();
	    	 
	    	 Iterator it = element.getChildElements();

	    	 SOAPElement el = null;

	    	 while (it.hasNext()) {

	    	 el = (SOAPElement) it.next();
	    	 System.out.println("el--"+el);
	    	 if ("value".equals(el.getLocalName())) {

	    	  tag_result.setValue(Float.valueOf(el.getValue()));

	    	System.out.println("#### " + el.getLocalName() + " ==== " + el.getValue());

	    	 } else if ("paramConfigId".equals(el.getLocalName())) {

	    		 tag_result.setParamConfigId(Long.valueOf(el.getValue()));

	    	 System.out.println("#### " + el.getLocalName() + " ==== " + el.getValue());

	    	 } else if ("tag".equals(el.getLocalName())) {

	    		 tag_result.setTag(el.getValue());

	    	 System.out.println("#### " + el.getLocalName() + " ==== " + el.getValue());

	    	 }

	    	 }
	    	 list.add(tag_result);
	    	 } else if (null == element.getValue()

	    	 && element.getChildElements().hasNext()) {

	    	 parse_list(element.getChildElements(), new Tag_result());

	    	 }
	    	 }
	    	 return list;
	    	 }
	     
	     
	     public List<Tag_result> getPicklistFromSoapResponse(String soapResponse) throws ServiceException {
	    	 
	    	 Map values = new LinkedHashMap();
	    	 
	    	 List<Tag_result> list=new ArrayList();

	    	 XMLInputFactory inputFactory = XMLInputFactory.newInstance();

	    	 String code = null;

	    	 String display = null;

	    	 String disabled = null;

	    	 try {
	    	 System.out.println("soapResponse--"+soapResponse);
	    	 InputStream in = new ByteArrayInputStream(soapResponse.getBytes(StandardCharsets.UTF_8));
	    	 //InputStream inputStream = convertStringToInputStream(soapResponse);
	    	 System.out.println("in--"+in);
	    	 XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
             System.out.println("eventReader--"+eventReader);
	    	 while (eventReader.hasNext()) {
	    	 Tag_result tag_result=new Tag_result();
	    	 XMLEvent event = eventReader.nextEvent();

	    	 if (event.isStartElement()) {

	    	 if (event.asStartElement().getName().getLocalPart().equals("value")) {

	    	 event = eventReader.nextEvent();

	    	 code = event.asCharacters().getData();
	    	 tag_result.setValue(Float.valueOf(event.asCharacters().getData()));
	    	 
	    	 continue;

	    	 }

	    	 if (event.asStartElement().getName().getLocalPart().equals("paramConfigId")) {

	    	 event = eventReader.nextEvent();

	    	 display = event.asCharacters().getData();
	    	 tag_result.setParamConfigId(Long.valueOf(event.asCharacters().getData()));
	    	 continue;

	    	 }

	    	 if (event.asStartElement().getName().getLocalPart().equals("tag")) {

	    	 event = eventReader.nextEvent();

	    	 disabled = event.asCharacters().getData();
	    	 tag_result.setTag(event.asCharacters().getData());
	    	// if ( "Y".equals(disabled)) values.put(code, display);

	    	 continue;

	    	 }
	    	 System.out.println("event.asStartElement().getName().getLocalPart()--"+event.asStartElement().getName());
	    	 list.add(tag_result);
	    	 }
	    	
	    	 }

	    	 } catch (XMLStreamException e) {

	    	

	    	 }

	    	 return list;

	    	 }
	    	 
	    
	     
	   
	     
	    /*
	     public  List<Map<String, String>> responseWebList(String response, String table) {
	         //创建Reader对象
	         SAXReader reader = new SAXReader();
	         //加载xml
	         Document document = null;
	         List<Map<String, String>> requestList = new ArrayList<>();
	         Map<String, String> request = new HashMap();
	         try {
	             //获取数据流
	             InputStream is = new ByteArrayInputStream(response.getBytes());
	             document = reader.read(is);
	         } catch (DocumentException e) {
	             e.printStackTrace();
	         }
	         //获取根节点
	         Element rootElement = (Element) document.getRootElement();
	         Iterator iterator = ((org.dom4j.Element) rootElement).elementIterator();
	         while (iterator.hasNext()) {
	             Element stu = (Element) iterator.next();
	             //判断节点是否为Result 如果不是则向下遍历
	            // while (!((File) stu).getName().equals((table + "Result"))) {
	             while (!((File) stu).getName().equals((table + "Result"))) {
	                 if (((org.dom4j.Element) stu).elementIterator().hasNext()) {
	                     stu = (Element) ((org.dom4j.Element) stu).elementIterator().next();
	                 } else {
	                     return null;
	                 }
	             }
//	             List<Attribute> attributes = stu.attributes();
//	             System.out.println("======获取属性值======");
//	             for (Attribute attribute : attributes) {
//	                 System.out.println(attribute.getValue());
//	             }
	             //Log.d(TAG, "responseWebList: ======遍历子节点======");
	             Iterator iterator1 = ((org.dom4j.Element) stu).elementIterator();
	             while (iterator1.hasNext()) {
	                 Element stuChild = (Element) iterator1.next();
	                 if (((org.dom4j.Element) stuChild).elementIterator().hasNext()) {
	                     //Log.d(TAG, "responseWebList: ======遍历孙节点======");
	                     Iterator iterator2 = ((org.dom4j.Element) stuChild).elementIterator();
	                     request = new HashMap();
	                     while (iterator2.hasNext()) {
	                         Element stuSon = (Element) iterator2.next();
	                         //Log.d(TAG, "节点名：" + stuSon.getName() + "---节点值：" + stuSon.getStringValue());
	                         request.put(((File) stuSon).getName(), ((Node) stuSon).getStringValue());
	                     }
	                 }
	                 requestList.add(request);
	             }
	         }
	         System.out.println("requestList---"+requestList);
	         return requestList;
	     }
	  */
	     
}
